<template>
  <div class="main-app">
    <el-divider content-position="left">转运基本信息</el-divider>
    <el-row style="margin-top: -10px">
      <el-form ref="form" :model="form" label-width="200px">
        <el-col :span="12">

          <el-form-item label="处置单位名称:" required prop="disposalId">
            <el-select v-model="form.disposalId" placeholder="请选择" style="width: 90%;" @change="selectedDealUnit">
              <el-option v-for="item in deallUnitList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="出库批次号:" required prop="batchLabel">
            <el-input v-model="form.batchLabel" style="width: 90%;" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="通讯地址:">
            <el-input v-model="form.address" disabled style="width: 90%;" />
          </el-form-item>

        </el-col>
      </el-form>
    </el-row>
    <el-divider content-position="left">拟转移危险类别</el-divider>
    <el-row style="margin-top: 10px; padding: 10px">
      <el-form :inline="true" class="form-inline">
        <el-form-item>
          <el-button type="primary" icon="el-icon-plus" @click="typeAdd">添加转移废物</el-button>
        </el-form-item>
        <el-form-item>
          <div>累计转移数量 ：{{ form.number }}</div>
        </el-form-item>
        <el-form-item>
          <el-divider direction="vertical" />
        </el-form-item>
        <el-form-item>
          <div>累计转移重量 ：{{ form.wastWeight }} 吨</div>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row style="margin-top: -10px">
      <el-table :data="form.tableData" border style="width: 100%">
        <el-table-column prop="name" label="废物名称" width="180" />

        <el-table-column prop="categoryContent" label="废物类别" />
        <el-table-column prop="codeId" label="废物代码" />
        <el-table-column prop="characteristicContent" label="危险特性" />
        <el-table-column prop="physicalProperties" label="废物形态">
          <template slot-scope="scope">
            <el-tag size="medium" style="width: 100%; text-align: center;" effect="dark">
              {{ scope.row.physicalProperties |parsePhysicalProperties }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hazardousSubstancesName" label="危害成分" />
        <el-table-column prop="containerCategory" label="容器类型">
          <template slot-scope="scope">
            <el-tag size="medium" style="width: 100%; text-align: center;" effect="dark">
              {{ scope.row.containerCategory | parseContainerCategory }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="wastWeight" label="本次出库重量 (吨)" width="180">
          <template slot-scope="scope">
            <el-input v-model="scope.row.wastWeight" type="number" placeholder="请输入转运重量..." @keyup.enter.native="addWasteWeight"
                      @blur="addWasteWeight"
            />
          </template>
        </el-table-column>
        <el-table-column prop="inAmount" label="废物库存量(吨)" />
        <el-table-column label="备注原因">
          <template slot-scope="scope">
            <el-select v-model="form.tableData[scope.$index].remarksId" placeholder="请选择" clearable style="width: 90%;">
              <el-option v-for="item in resultRemarkList" :key="item.code" :label="item.value" :value="item.code" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!--      <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">编辑</el-button> -->
            <el-button size="mini" type="danger" @click="deleteRow(scope.$index, form.tableData)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-row>
    <el-row style="margin-top: 20px; text-align: center">
      <el-form :inline="true" class="form-inline">

        <el-form-item>
          <el-button type="success" :loading="isInstoreing" @click="save()">创建联单</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-row>
  </div>
</template>

<script>
// Table组件相关逻辑，需要引用
import {
  pageMixin
} from "../../../mixins/index";
import {
  PhysicalProperties,
  ContainerType
} from "../../../utils/resource.js";
import {
  getTransportApplyInfoById,
  getApplyWastList,
  getTransportPlanWastList
} from '../../../api/wastereceipt.js';
import {
  CreateHWReceipt
} from '../../../api/warehouse.js';

import {
  getUnitInfoByType,
  getDictionaryListByType,
  getUnitInfoById
} from '../../../api/system.js';

import {
  parseTime,
  getFloat,
  parseStartAndEndTimeList,

  getInOutCode
} from '../../../utils/index.js';
export default {
  filters: {
    parseDate(value) {
      if (value) {
        return value.replace("T", " ");
      }
    },

    parsePhysicalProperties(value) {
      if (value != null) {
        return PhysicalProperties.find((p) => p.value === `${value}`).label;
      }
    },
    parseContainerCategory(value) {
      if (value != null) {
        return ContainerType.find((p) => p.value === `${value}`).label;
      }
    },

  },
  mixins: [pageMixin],
  data() {
    return {
      isInstoreing: false,
      form: {
        id: "",
        disposalId: "",

        transportPlanId: "",
        transferPlanNumber: "",

        productUnitObj: {},
        ccId: "",
        collectionUnitObj: {},

        tcId: "",
        transportUnitObj: {

        },
        startProposedTransferTime: "",
        endProposedTransferTime: "",

        transportTime: [],

        number: 0,
        wastWeight: 0,

        tableData: [],
      },
      selectedDisposalUnitObj: {},

      collectionUnitList: [],
      productUnitList: [],
      transportUnitList: [],

      resultRemarkList: [],
      deallUnitList: [],

      rules: {

        batchLabel: [{
          required: true,
          message: "请填写出库批次号",
          trigger: "blur"
        }],
        disposalId: [{
          required: true,
          message: "请填选择处置单位",
          trigger: "blur"
        }],

      },
    };
  },
  async created() {
    // 获取运输单位list
    var searchData = {
      searchParam: JSON.stringify({
        Type: "40",
		 AreaNumber:  this.$store.state.user.userObj.areaNumberStr,
      })
    }
    var searchData2 = {
      searchParam: JSON.stringify({
        Type: "10",
		 AreaNumber:  this.$store.state.user.userObj.areaNumberStr,
      })
    }
    // var searchData3 = {
    //   searchParam: JSON.stringify({
    //     "Type": "20"
    //   })
    // }
    var userObj = this.$store.state.user.userObj;
    // 并行获取数据
    Promise.all([await getUnitInfoByType(searchData), await getUnitInfoByType(searchData2),
      await getUnitInfoById(userObj.orgGuid)
    ])
      .then((result) => {
        this.transportUnitList = result[0].data;
        this.collectionUnitList = result[1].data;
        this.form.productUnitObj = result[2].data;
      })
      .then(async() => {
        var tempFormInfo = JSON.parse(localStorage.getItem('tempFormInfo'));
        if (tempFormInfo) {
          this.form = tempFormInfo;
          this.init();
        } else {
          const {
            id
          } = this.$route.params;
          if (id) {
            this.form.id = id;
            await this.getTransportApplyInfoById(id);
          } else {
            this.init();
          }
        }
      })
  },
  methods: {

    deleteRow(index, rows) {
      rows.splice(index, 1);
      this.form.number = this.form.tableData.length;
      this.addWasteWeight();
    },
    async init() {
      await this.getOtherInfo();
      this.form.number = this.form.tableData.length;
      this.addWasteWeight();
      this.form.batchLabel = "CK" + getInOutCode();

      if (!this.form.tcId) {
        if (this.transportUnitList) {
          this.form.tcId = this.transportUnitList[0].id;
          this.form.transportUnitObj = this.transportUnitList[0];
          this.form.tcName = this.form.transportUnitObj.name;
          this.form.tcAddress = this.form.transportUnitObj.detailedAddress;
        }
      } else {
        this.form.transportUnitObj = {
          id: "",
          name: "",
          detailedAddress: ""
        };
        this.form.transportUnitObj.id = this.form.tcId;
        this.form.transportUnitObj.name = this.form.tcName;
        this.form.transportUnitObj.detailedAddress = this.form.tcAddress;
      }

      if (!this.form.ccId) {
        if (this.collectionUnitList) {
          this.form.ccId = this.collectionUnitList[0].id;
          this.form.collectionUnitObj = this.collectionUnitList[0];
          this.form.ccName = this.form.collectionUnitObj.name;
          this.form.ccAddress = this.form.collectionUnitObj.detailedAddress;
        }
      } else {
        this.form.collectionUnitObj = {
          id: "",
          name: "",
          detailedAddress: ""
        }
        this.form.collectionUnitObj.id = this.form.ccId;
        this.form.collectionUnitObj.name = this.form.ccName;
        this.form.collectionUnitObj.detailedAddress = this.form.ccAddress;
      }
      // 设置时间
      if (!this.form.startProposedTransferTime) {
        this.form.transportTime = [];
      } else {
        this.form.startProposedTransferTime = this.form.startProposedTransferTime.replace("T", " ");
        this.form.endProposedTransferTime = this.form.endProposedTransferTime.replace("T", " ");
        this.form.transportTime = parseStartAndEndTimeList(this.form.startProposedTransferTime, this.form
          .endProposedTransferTime);
      }
    },
    selectedDealUnit(val) {
      var obj2 = this.deallUnitList.find((p) => p.id === `${val}`);
      if (obj2) {
        this.selectedDisposalUnitObj = obj2;
        this.form.disposalId = obj2.id;
        this.form.disposalName = obj2.name;
        this.form.address = obj2.detailedAddress
      } else {
        this.form.address = "";
      }
    },
    async getOtherInfo() {
      // 获取运输单位list
      var searchData = {
        searchParam: JSON.stringify({
          Type: "30",
		  AreaNumber:  this.$store.state.user.userObj.areaNumberStr,
        })
      }
      // 并行获取数据
      Promise.all([await getDictionaryListByType("101"), await getUnitInfoByType(searchData)])
        .then((result) => {
          this.deallUnitList = [];
          this.resultRemarkList = result[0].data;

          this.deallUnitList = result[1].data;
          if (this.deallUnitList) {
            if (!this.form.disposalId) {
              this.selectedDisposalUnitObj = this.deallUnitList[0];
            } else {
              this.selectedDealUnit(this.form.disposalId)
            }
          }
        })
    },

    async getTransportApplyInfoById(id) {
      var searchData = {
        limit: this.pageSize,
        page: this.currentPage,
        searchParam: JSON.stringify({
          TransferApplyId: id
        })
      }
      this.loading = true;
      this.form.tableData = [];
      Promise.all([await getTransportApplyInfoById(this.form.id), await getApplyWastList(searchData)])
        .then((result) => {
          var obj = this.form.productUnitObj;

          this.form = result[0].data;
          this.form.productUnitObj = obj;
          result[1].data.forEach(item => {
            item.id = item.hazardousWasteId;
          })
          this.form.tableData = result[1].data;
          this.total = result[1].count;
          this.init();
          this.loading = false;
        })
    },

    addWasteWeight() {
      this.form.wastWeight = 0;

      this.form.tableData.forEach(item => {
        if (item.wastWeight < 0) {
          item.wastWeight = 0
        }

        this.form.wastWeight += getFloat(item.wastWeight, 5)
        console.log(this.form.wastWeight);
      })

      this.form.wastWeight = getFloat(this.form.wastWeight, 5)
    },

    async getTransportPlanInfoById(id) {
      var searchData = {
        limit: this.pageSize,
        page: this.currentPage,
        searchParam: JSON.stringify({
          TransferPlanId: id,
        })
      }
      this.loading = true;
      this.form.tableData = [];
      Promise.all([await getTransportPlanWastList(searchData)])
        .then((result) => {
          this.form.tableData = result[1].data;

          this.total = result[1].count;
          this.loading = false;
        })
    },

    collectionUnitChange(val) {
      // this.ccId = val;
      this.form.ccId = val;
      this.form.collectionUnitObj = this.collectionUnitList.find((p) => p.id === val)
      this.form.ccName = this.form.collectionUnitObj.name;
      this.form.ccAddress = this.form.collectionUnitObj.detailedAddress;
    },
    transportUnitChange(val) {
      // this.TcId = val;
      this.form.tcId = val;
      this.form.transportUnitObj = this.transportUnitList.find((p) => p.id === val)
      this.form.tcName = this.form.transportUnitObj.name;
      this.form.tcAddress = this.form.transportUnitObj.detailedAddress;
    },

    changeTransportTime() {
      this.form.startProposedTransferTime = parseTime(this.form.transportTime[0])
      this.form.endProposedTransferTime = parseTime(this.form.transportTime[1])
    },

    // 除数，被除数， 保留的小数点后的位数
    Chufunction(arg1, arg2, digit) {
      var t1 = 0;
      var t2 = 0;
      var r1;
      var r2;
      console.log(arg1);
      console.log(arg2);
      try {
        t1 = arg1.toString().split(".")[1].length
      } catch (e) {
        console.log("错误:" + e.message);
      }
      try {
        t2 = arg2.toString().split(".")[1].length
      } catch (e) {
        console.log("错误:" + e.message);
      }
      r1 = Number(arg1.toString().replace(".", ""))
      r2 = Number(arg2.toString().replace(".", ""))
      // 获取小数点后的计算值
      var result = ((r1 / r2) * Math.pow(10, t2 - t1)).toString();

      var result2 = result.split(".")[1];
      if (result2 === "" || result2 === null || result2 === undefined) {
        return Number(result.split(".")[0]);
      } else {
        result2 = result2.substring(0, digit > result2.length ? result2.length : digit);
        return Number(result.split(".")[0] + "." + result2);
      }
    },

    save(type) {
      // 校验必填项
      this.$refs["form"].validate(async(valid) => {
        if (valid) { // 校验成功
          const message = "操作成功";
          if (this.form.tableData.length === 0) {
            this.$message.error('请选择转移废物内容');
            return;
          }
          var wastWeight = this.form.tableData.findIndex(item => {
            return item.wastWeight === 0;
          })
          if (wastWeight > -1) {
            this.$message.error('请将列表内废物的转移重量填写完全');
            return;
          }

          var tempTotalWeight = 0;
          var tempTotalWeight_Origianl = 0;
          var wasteObjs = [];

          for (let i = 0; i < this.form.tableData.length; i++) {
            tempTotalWeight += getFloat(this.form.tableData[i].wastWeight, 5);
            tempTotalWeight_Origianl += this.form.tableData[i].inAmount;

            var describ = "";
            if (this.form.tableData[i].remarksId) {
              var resNum = this.resultRemarkList.findIndex(item => {
                return item.code === this.form.tableData[i].remarksId
              })
              if (resNum > -1) {
                describ = this.resultRemarkList[resNum].value
              }
            }
            var obj = {
              HwId: this.form.tableData[i].id,
              InAmount: this.form.tableData[i].wastWeight,
              Describe: describ,
            }
            wasteObjs.push(obj);

            // if (i === 0) {
            //   wastIds += this.form.tableData[i].id;
            //   wastWeights += this.form.tableData[i].wastWeight.toString();
            // } else {
            //   wastIds += ("," + this.form.tableData[i].id)
            //   wastWeights += ("," + this.form.tableData[i].wastWeight.toString())
            // }
          }

          if (tempTotalWeight <= 0) {
            this.$message.error('出库重量需大于0');
            return;
          }

          var text = `本次合计出库${tempTotalWeight}吨, 是否继续?`;
          if (getFloat(tempTotalWeight, 5) !== getFloat(tempTotalWeight_Origianl, 5)) {
            var mm = this.Chufunction(Math.abs(tempTotalWeight_Origianl - tempTotalWeight),
              tempTotalWeight_Origianl, 4) * 100;
            if (mm.toString().length > 5) {
              mm = mm.toString().substr(0, 5); // 截取从第1个开始往后数5位之间的字符
            }

            // text = `本次出库${this.form.outAmount}吨，原始库存${this.form.wastObj.inAmount}吨, 损耗率为${mm}%，是否确认?`;
            var textType = "损耗率";
            if (tempTotalWeight > tempTotalWeight_Origianl) {
              textType = "误差率";
            }
            text =
                `本次合计出库<span style="color:red; font-size: 18px; font-weight: 700;">${tempTotalWeight}吨</span>，原始库存<span style="color:red; font-size: 18px; font-weight: 700;">${tempTotalWeight_Origianl}吨</span>, ${textType}为<span style="color:red; font-size: 18px; font-weight: 700;">${mm}%</span>，是否确认?`;
          }

          this.$confirm(text, "提示", {
            dangerouslyUseHTMLString: true, // 开启Html时用
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(async() => {
            var param = {
              "HwData": JSON.stringify(wasteObjs),
              "TotalOutWeight": tempTotalWeight,
              "BatchLabel": this.form.batchLabel,
              "DisposalMethod": "贮存",
              "CollectionId": this.selectedDisposalUnitObj.id,
              "CollectionName": this.selectedDisposalUnitObj.name,
              "CollectionProvince": this.selectedDisposalUnitObj.province,
              "CollectionCity": this.selectedDisposalUnitObj.city,
              "CollectionArea": this.selectedDisposalUnitObj.area,
              "CollectionAddress": this.selectedDisposalUnitObj.detailedAddress,
              "CollectionContactsId": this.selectedDisposalUnitObj.epUserId,
              "CollectionContactsName": this.selectedDisposalUnitObj.epUserName,
              "CollectionContactsPhone": this.selectedDisposalUnitObj.epUserPhone,
              "Remarks": "",
            }

            this.isInstoreing = true;
            const {
              success,
              msg
            } = await CreateHWReceipt(param);
            if (success) {
              // 清除转运申请详情存在localstroage的临时表单内容
              localStorage.removeItem('tempFormInfo');
              this.$notify({
                title: "成功",
                message: message,
                type: "success",
                duration: 3000,
              });
              this.$router.push("/warehouse/outhouse_ByTransport");
              this.isInstoreing = false;
            } else {
              this.isInstoreing = false;
              this.$notify.error({
                title: "失败",
                message: msg,
                duration: 3000,
              });
            }
          });
        }
      });
    },
    typeAdd() {
      localStorage.setItem('tempFormInfo', JSON.stringify(this.form));
      this.$router.push("/warehouse/outhouse_ByTransport/index_WastObjList");
    },
    cancel() {
      // 清除转运申请详情存在localstroage的临时表单内容
      localStorage.removeItem('tempFormInfo');
      this.$router.push("/warehouse/outhouse_ByTransport");
    },
  },
};
</script>
